//
//  StatusHomeViewModel.swift
//  weibo19
//
//  Created by Arvin on 15/11/16.
//  Copyright © 2015年 Arvin. All rights reserved.
//

import UIKit
import SDWebImage


class StatusHomeViewModel: NSObject {

    class func loadStatusDate(max_id  max_id: Int,since_id: Int, finished: (statuses: [Status]?) -> ()) {
        let token = UserAccountViewModel().account?.access_token
        var params = [String: AnyObject]()
        params["access_token"] = token
        
        if since_id > 0 {
            params["since_id"] = since_id
        }
        
        if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        
        let urlStr = "2/statuses/friends_timeline.json"

        NetworkTools.sharedTools.requestJSONData(.GET, urlSting: urlStr, parma: params) { (result, error) -> () in
            if error != nil {
                finished(statuses: nil)
                return
            }
            
            // 获取全部statuus, 注意: 后面的数据类型
            let arr = result!["statuses"] as? [[String: AnyObject]]
            var list = [Status]()
            for item in arr! {
                let status = Status(dict: item)
                list.append(status)
            }
            // 下载单张图片
            downloadPicture(list, finished: finished)
        }
    }
    // 这里只下载了原创微博的图片, 没有下在转发微博的图片
    private class func downloadPicture(array: [Status], finished: (statuses: [Status]?) -> ()) {
        if array.count == 0 {
            // 这里要进行回调
            finished(statuses: array)
            return
        }
        // 任务组
       let  group = dispatch_group_create()
        dispatch_group_enter(group)
        for status in array {
           let URLs = status.pic_URLs
            
            if URLs?.count != 1 {
                continue
            }
            
            let URL = URLs?.last
            // 下载图片
            SDWebImageManager.sharedManager().downloadImageWithURL(URL, options: [], progress: { (_, _) -> Void in
                }, completed: { (_, _, _, _, _) -> Void in
            })
        }
        dispatch_group_leave(group)

        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
             finished(statuses: array)
        }
    }
    
}
